<template>
  <div id="comparison">
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="700px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleCancel">
      <div class="comp">
        <component ref="dialog" :is="isWhitchDialogComp" @checkboxChange="checkboxChange" @setFeedbackChecked="setFeedbackChecked" :visibility="conflictDialogCheckBox" :lawContrastResult="lawContrastResult" :compareId="compareId"></component>
      </div>
      <div class="btn" slot="footer">
        <div class="feedback" v-if="feedbackBool">
          <div class="hint" v-if="conflictDialogCheckBox">
            <!-- <span>我们会根据您的反馈意见优化算法，反馈意见不会改变冲突检测结果。</span> -->
          </div>
          <div class="btn-box" v-else>
            <span>结果不准确?</span>
            <el-button class="feedback-btn" size="mini" @click="feedback">反馈意见</el-button>
          </div>
        </div>
        <el-button size="mini" @click="handleCancel" class="cancel">取消</el-button>
        <el-button type="primary" size="mini" @click="handleComparison" class="comparison">{{btnTxt}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import DefaultDialog from './dialog/default-dialog'
import ConfilctDialog from './dialog/conflict-dialog'
import NoConfilctDialog from './dialog/no-conflict-dialog'
import { mapGetters } from 'vuex'
import _ from 'lodash'
export default {
  components: {
    DefaultDialog,
    ConfilctDialog,
    NoConfilctDialog
  },
  filters: {},
  props: {

  },
  data () {
    return {
      title: '选择法规对比',
      dialogBool: 0,
      dialogVisible: false,
      btnTxt: '对比',
      checkBoxPitchResult: null,
      compareId: null, // 对比记录id
      timer: null,
      conflictDialogCheckBox: null, // 对比结果有冲突里的多选框
      lawContrastResult: null, // 对比结果
      defaultCheckLaw: null,
      feedbackBool: false, // 反馈btn
      feedbackChecked: [], // 反馈意见多选框组选中结果
      checkboxChecked: [], // 从接口获取多选框的状态用来和feedbackChecked进行比对、如果没有发生任何改变禁用提交反馈按钮
      loadOptions: {
        target: '#default-dialog',
        text: '对比中，请等待...',
        spinner: 'el-icon-loading'
      }
    }
  },
  computed: {
    ...mapGetters({
      userInfo: 'userInfo',
      token: 'token'
    }),
    isWhitchDialogComp () {
      let dialogComp = ['DefaultDialog', 'ConfilctDialog', 'NoConfilctDialog']
      return dialogComp[this.dialogBool]
    }
  },
  watch: {
    lawContrastResult: {
      handler () {
        this.closeLoading()
      },
      deep: true
    }

  },
  created () {},
  mounted () {
  },
  activated () {},
  beforeDestroy () {},
  methods: {
    showDialog () {
      this.dialogVisible = true
    },
    handleCancel (bool) {
      if (this.btnTxt === '提交反馈意见') {
        this.closeFeedbackBtn()
        return
      }
      this.closeTimer()
      this.dialogVisible = false
      this.dialogBool = 0
      this.btnTxt = '对比'
      this.title = '选择法规对比'
      this.feedbackBool = false
    },
    feedback () {
      this.checkboxChecked = []
      this.lawContrastResult.clash_data.forEach(outerItem => {
        outerItem.clash_list.forEach(innerItem => {
          this.checkboxChecked.push({ id: innerItem.id, compare_review: innerItem.compare_review })
        })
      })
      this.feedbackChecked = _.cloneDeep(this.checkboxChecked)
      this.openFeedbackBtn()
    },
    handleComparison () {
      if (this.btnTxt === '确定') {
        this.handleCancel()
        return
      }
      if (this.checkBoxPitchResult.length === 1) {
        this.$msgMnger.warn('请选择要进行对比的法规')
        return
      }
      var defaultCheckLaw = JSON.parse(sessionStorage.getItem('setDeafultCheckLaw')) // 获取默认法规的详细信息
      var params = {
        compare_type: 1,
        law_ids: JSON.stringify(this.checkBoxPitchResult.slice(1)),
        user_id: Number(this.userInfo.id),
        muster_id: Number(defaultCheckLaw.id)
      }
      if (this.btnTxt === '对比') {
        this.creatContrast(params)
        return
      }
      if (this.feedbackChecked.length === 0) {
        this.$message.error('请选择要反馈的冲突点')
        return
      }
      if (this.btnTxt === '提交反馈意见') {
        this.submitFeedback()
      }
    },
    creatContrast (params) {
      if (this.timer !== null) {
        return
      }
      this.openLoading()
      this.$api.creatContrast(params).then(res => {
        this.compareId = res.data.compare_id
        this.openTimer(res.data.compare_id)
      }).catch(err => {
        this.$msgMnger.httpError(err)
        this.closeLoading()
      })
    },
    setFeedbackChecked (val) {
      this.feedbackChecked = val
    },
    submitFeedback () {
      if (this.feedbackChecked.length === 0) {
        return
      }
      this.openLoading()
      var params = {
        review_data: JSON.stringify(this.feedbackChecked)
      }
      this.$api.submitFeedback(params).then(res => {
        console.log(res)
        this.closeLoading()
        this.$msgMnger.success('反馈成功')
      }).catch(err => {
        console.log(err)
        this.closeLoading()
        this.$msgMnger.error('反馈失败')
      })
    },
    getContrastStatus (compareId) {
      this.$api.getContrastStatus(compareId).then(res => {
        if (res.data.status === 3) {
          this.getContrastResult(compareId)
          this.closeTimer()
        }
        if (res.data.status === 4) {
          this.$msgMnger.error('对比失败')
          this.closeTimer()
        }
      }).catch(err => {
        this.$msgMnger.httpError(err)
        console.log(err)
      })
    },
    getContrastResult (id) {
      this.$api.getContrastResult(id).then(res => {
        this.lawContrastResult = res.data
        if (res.data.result === 1) {
          this.dialogBool = 1
          this.feedbackBool = true
        } else {
          this.dialogBool = 2
        }
        this.btnTxt = '确定'
        this.title = '法规对比结果'
        this.closeLoading()
      }).catch(err => {
        console.log(err)
        this.$msgMnger.httpError(err)
        this.closeLoading()
      })
    },
    openLoading () {
      Loading.service(this.loadOptions)
    },
    closeLoading () {
      // var loadingInstance = Loading.service(this.loadOptions)
      // this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
      Loading.service(this.loadOptions).close()
      // })
    },
    openFeedbackBtn () {
      this.conflictDialogCheckBox = true
      this.btnTxt = '提交反馈意见'
      this.title = '法规对比结果反馈意见'
    },
    closeFeedbackBtn () {
      this.conflictDialogCheckBox = false
      this.btnTxt = '确定'
      this.title = '对比结果'
    },
    openTimer (compareId) {
      this.timer = setInterval(() => {
        setTimeout(() => this.getContrastStatus(compareId), 0)
      }, 3000)
    },
    closeTimer () {
      clearInterval(this.timer)
      this.timer = null
    },
    checkboxChange (val) {
      this.checkBoxPitchResult = val
      console.log(val)
    },
    btnDisabled () {
      return _.isEqual(this.checkboxChecked, this.feedbackChecked) && this.btnTxt === '提交反馈意见'
    }
  }
}
</script>

<style lang="scss" scoped>

#comparison {
  width: 756px;
  height: auto;
  .comp {
    padding: 0 15px;
  }
  .btn {
    width: 100%;
    height: 64px;
    border-radius: 0 0 6px 6px;
    box-sizing: border-box;
    padding-right: 24px;
    background: $box-title-bg-color;
    .download, .comparison, .cancel {
      height: 32px;
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }
    .comparison{
      width: auto;
      min-width: 65px;
    }
    .cancel {
      width: 65px;
      border: none;
      background: transparent;
      color: $sedondary-text-color;
    }
    .feedback{
      float: left;
      position: relative;
      top: 50%;
      transform: translateY(-50%);
      font-size: 12px;
      .btn-box{
        span{
          margin: 0 5px 0 73px;
          color: $sedondary-text-color;
        }
        .feedback-btn{
          width:72px;
          height:28px;
          border:1px solid rgba(48,128,254,1);
          color: #3080FE;
          background: transparent;
          text-align: center;
          padding: 0;
        }
        .feedback-btn:hover{
          color: #FFFFFF;
          background-color: #3080FE;
          border-color: #3080FE;
        }
      }
      .hint{
        span{
          font-size: 12px;
          margin-left: 24px;
          color: $sedondary-text-color;
        }
      }
    }

  }
}
</style>

<style lang="scss">

#comparison {
  position: relative;
  .el-dialog{
    width: 756px !important;
    border-radius: 8px;
    margin-top: 7vh !important;
    .el-dialog__header{
      background: #252C43;
      border-radius: 6px 6px 0 0;
      padding: 0 20px;
      height: 48px;
      line-height: 48px;
      .el-dialog__title{
        color: $header-text-color;
      }
    }
    .el-dialog__footer{
      padding: 0;
    }
  }
}
</style>
